﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.Reflection;
using System.Windows.Forms;
using LogLib;

namespace KXmlUIControl
{
    public class XmlPageReader
    {
        /// <summary>
        /// 最新错误信息
        /// </summary>
        public string Error { get; private set; }
       
        private string _file = "";
   
   
        private XDocument _xmlDoc = null;
        private XElement _root = null;

        /// <summary>
        /// 主窗口配置信息
        /// </summary>
        //public XmlConfigForm MainFormConfig { get; private set; } = null;

        /// <summary>
        /// 子窗口配置信息
        /// </summary>
        //public XmlConfigForm ChildFormConfig { get; private set; } = null;

        public XmlPageReader(string file)
        {
            _file = file; 
        }

        public bool TryLoadFormConfig(bool isMainForm, out XmlConfigForm formConfig)
        {
            formConfig = null;           
            if (!OpenXmlDOC())
            {
                return false;
            }
            try
            {
                XElement formRoot = null;
                if (isMainForm)
                {
                    formRoot = _root.Element("MainWindow");
                    formConfig = new XmlConfigForm(formRoot, true);
                }
                else
                {
                    formRoot = _root.Element("SubWindow");
                    formConfig = new XmlConfigForm(formRoot, false);
                }
                formConfig.LoadConfig();
                string typeVal = _root.Attribute("Type").Value.Trim();
                WindowType FormType = (WindowType)Enum.Parse(typeof(WindowType), typeVal);
                formConfig.FormType = FormType;
            }
            catch (Exception ex)
            {
                Error = string.Format("配置文件{0}加载错误:{1}", _file, ex.Message);
                Log.WriteExceptionAsync(ex.ToString());
                return false;
            }
            return true;
        }

        private bool OpenXmlDOC()
        {
            try
            {
                _xmlDoc = XDocument.Load(_file);
                _root = _xmlDoc.Element("Windows");
                return true;
            }
            catch (Exception ex)
            {
                Error = string.Format("配置文件{0}加载错误:{1}", _file, ex.Message);
                Log.WriteExceptionAsync(ex.ToString());
                return false;
            }    
        }     
    }
}
